import { Order, Vehicle, Route, Financial, DashboardStats, Cargo, Product, OrderProduct } from '../types';

// 模拟数据生成器
const generateMockData = () => {
  const now = new Date();
  const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  
  // 产品数据
  const products: Product[] = Array.from({ length: 20 }, (_, index) => {
    const productNames = [
      '电子产品A', '电子产品B', '服装类商品', '食品饮料', '建筑材料',
      '化工产品', '医疗器械', '汽车配件', '家具用品', '纺织原料',
      '机械设备', '钢铁制品', '塑料制品', '纸制品', '玻璃制品',
      '陶瓷制品', '橡胶制品', '木制品', '金属制品', '皮革制品'
    ];
    
    return {
      id: `PROD-${String(index + 1).padStart(4, '0')}`,
      name: productNames[index] || `产品${index + 1}`,
      skuCode: `SKU${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
      unit: ['件', '箱', '吨', '立方米', '套'][Math.floor(Math.random() * 5)],
      unitPrice: Math.floor(Math.random() * 5000) + 100,
      stock: Math.floor(Math.random() * 1000) + 50,
      createdAt: new Date(oneWeekAgo.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date().toISOString(),
    };
  });

  // 订单数据
  const orders: Order[] = Array.from({ length: 50 }, (_, index) => {
    const id = `ORD-${String(index + 1).padStart(6, '0')}`;
    const orderTypes: Order['orderType'][] = ['town_internal', 'town_external'];
    const orderType = orderTypes[Math.floor(Math.random() * orderTypes.length)];
    const status = 'completed'; // 所有订单都设置为已完成状态
    const createdAt = new Date(oneWeekAgo.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000);
    
    // 为每个订单生成1-5个产品
    const orderProducts: OrderProduct[] = Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, prodIndex) => {
      const product = products[Math.floor(Math.random() * products.length)];
      const rolls = Math.floor(Math.random() * 50) + 1;
      
      return {
        id: `OP-${id}-${prodIndex + 1}`,
        orderId: id,
        productId: product.id,
        productName: product.name,
        skuCode: product.skuCode,
        rolls,
        unitPrice: 0,
        totalPrice: 0
      };
    });

    const totalRolls = orderProducts.reduce((sum, p) => sum + p.rolls, 0);
    
    return {
      id,
      orderNumber: id,
      userName: `客户${index + 1}`,
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      totalRolls,
      orderType,
      orderDate: createdAt.toISOString().split('T')[0],
      orderTime: createdAt.toTimeString().split(' ')[0].substring(0, 5),
      status,
      createdAt: createdAt.toISOString(),
      updatedAt: new Date().toISOString(),
      products: orderProducts,
      notes: '',
    };
  });

  const vehicles: Vehicle[] = Array.from({ length: 20 }, (_, index) => {
    const plateNumber = `京A${String(Math.floor(Math.random() * 100000)).padStart(5, '0')}`;
    const statuses: Vehicle['status'][] = ['available', 'in_use', 'maintenance', 'offline'];
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    
    return {
      id: `VEH-${String(index + 1).padStart(4, '0')}`,
      plateNumber,
      type: ['小型货车', '中型货车', '大型货车', '冷藏车'][Math.floor(Math.random() * 4)],
      capacity: [2, 5, 10, 15][Math.floor(Math.random() * 4)],
      status,
      location: {
        lat: 39.9042 + (Math.random() - 0.5) * 0.5,
        lng: 116.4074 + (Math.random() - 0.5) * 0.5,
        address: `北京市朝阳区某街道${Math.floor(Math.random() * 100)}号`,
      },
      driverId: `DRV-${String(index + 1).padStart(4, '0')}`,
      driverName: `司机${index + 1}`,
      driverPhone: `139${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      fuelConsumption: Math.floor(Math.random() * 20) + 10,
      mileage: Math.floor(Math.random() * 200000) + 10000,
      lastMaintenance: new Date(now.getTime() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString(),
    };
  });

  const routes: Route[] = Array.from({ length: 15 }, (_, index) => ({
    id: `ROUTE-${String(index + 1).padStart(3, '0')}`,
    name: `路线${index + 1}`,
    origin: ['北京', '上海', '广州'][Math.floor(Math.random() * 3)],
    destination: ['成都', '重庆', '西安'][Math.floor(Math.random() * 3)],
    distance: Math.floor(Math.random() * 2000) + 500,
    estimatedTime: Math.floor(Math.random() * 48) + 12,
    waypoints: [
      { name: '中转站1', lat: 39.9042, lng: 116.4074 },
      { name: '中转站2', lat: 30.2741, lng: 104.0668 },
    ],
    vehicleTypes: ['中型货车', '大型货车'],
    isActive: Math.random() > 0.2,
    createdAt: new Date(oneWeekAgo.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
  }));

  const paymentMethods = ['现金', '银行转账', '支付宝', '微信支付', '信用卡', '支票', '其他'];

  const financials: Financial[] = Array.from({ length: 100 }, (_, index) => {
    const type: Financial['type'] = Math.random() > 0.6 ? 'income' : 'expense';
    const categories = type === 'income' 
      ? ['运费收入', '仓储费', '包装费', '保险费']
      : ['燃油费', '过路费', '维修费', '工资', '保险费'];
    
    return {
      id: `FIN-${String(index + 1).padStart(6, '0')}`,
      type,
      category: categories[Math.floor(Math.random() * categories.length)],
      amount: Math.floor(Math.random() * 10000) + 100,
      description: `${type === 'income' ? '收入' : '支出'}描述${index + 1}`,
      date: new Date(oneWeekAgo.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      status: ['pending', 'completed', 'cancelled'][Math.floor(Math.random() * 3)] as any,
      paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
      invoiceNumber: Math.random() > 0.5 ? `INV-${String(index + 1).padStart(6, '0')}` : undefined,
    };
  });

  const cargos: Cargo[] = Array.from({ length: 30 }, (_, index) => {
    const cargoNames = [
      '电子产品', '服装鞋帽', '食品饮料', '建筑材料', '化工产品', 
      '医疗器械', '汽车配件', '家具用品', '纺织原料', '机械设备',
      '钢铁制品', '塑料制品', '纸制品', '玻璃制品', '陶瓷制品'
    ];
    const specifications = [
      '标准规格', '大型', '小型', '精密', '防潮', '易碎', '重型', '轻型'
    ];
    const units = ['件', '箱', '吨', '立方米', '套', '台', '个', '批'];
    
    return {
      id: `CARGO-${String(index + 1).padStart(4, '0')}`,
      name: cargoNames[Math.floor(Math.random() * cargoNames.length)],
      specification: Math.random() > 0.3 ? specifications[Math.floor(Math.random() * specifications.length)] : undefined,
      unit: units[Math.floor(Math.random() * units.length)],
      createdAt: new Date(oneWeekAgo.getTime() + Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date().toISOString(),
    };
  });

  return { orders, vehicles, routes, financials, cargos, products };
};

const mockData = generateMockData();

// 模拟API延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// Mock API 服务
export const mockApi = {
  // 仪表盘统计
  async getDashboardStats(): Promise<DashboardStats> {
    await delay(500);
    const orders = mockData.orders;
    const vehicles = mockData.vehicles;
    const financials = mockData.financials;
    
    return {
      totalOrders: orders.length,
      pendingOrders: 0, // 所有订单都是已完成状态
      completedOrders: orders.length, // 所有订单都是已完成状态
      exceptionOrders: 0, // 所有订单都是已完成状态
      totalRevenue: financials.filter(f => f.type === 'income').reduce((sum, f) => sum + f.amount, 0),
      totalCost: financials.filter(f => f.type === 'expense').reduce((sum, f) => sum + f.amount, 0),
      activeVehicles: vehicles.filter(v => v.status === 'in_use').length,
      totalVehicles: vehicles.length,
      onTimeDeliveryRate: 0.92,
      customerSatisfaction: 4.6,
    };
  },

  // 订单管理
  async getOrders(params?: { status?: string; orderType?: string; page?: number; limit?: number }): Promise<{ data: Order[]; total: number }> {
    await delay(300);
    let filteredOrders = mockData.orders;
    
    if (params?.status) {
      filteredOrders = filteredOrders.filter(order => order.status === params.status);
    }
    
    if (params?.orderType) {
      filteredOrders = filteredOrders.filter(order => order.orderType === params.orderType);
    }
    
    const page = params?.page || 1;
    const limit = params?.limit || 10;
    const start = (page - 1) * limit;
    const end = start + limit;
    
    return {
      data: filteredOrders.slice(start, end),
      total: filteredOrders.length,
    };
  },

  async getOrder(id: string): Promise<Order | null> {
    await delay(200);
    return mockData.orders.find(order => order.id === id) || null;
  },

  async createOrder(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt' | 'orderNumber'>): Promise<Order> {
    await delay(400);
    const newOrder: Order = {
      ...order,
      id: `ORD-${String(mockData.orders.length + 1).padStart(6, '0')}`,
      orderNumber: `ORD-${String(mockData.orders.length + 1).padStart(6, '0')}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockData.orders.unshift(newOrder);
    return newOrder;
  },

  async updateOrder(id: string, updates: Partial<Order>): Promise<Order | null> {
    await delay(300);
    const index = mockData.orders.findIndex(order => order.id === id);
    if (index === -1) return null;
    
    mockData.orders[index] = {
      ...mockData.orders[index],
      ...updates,
      updatedAt: new Date().toISOString(),
    };
    return mockData.orders[index];
  },

  async deleteOrder(id: string): Promise<boolean> {
    await delay(200);
    const index = mockData.orders.findIndex(order => order.id === id);
    if (index === -1) return false;
    
    mockData.orders.splice(index, 1);
    return true;
  },

  // 产品管理
  async getProducts(): Promise<Product[]> {
    await delay(300);
    return mockData.products;
  },

  async getProduct(id: string): Promise<Product | null> {
    await delay(200);
    return mockData.products.find(product => product.id === id) || null;
  },

  // 车辆管理
  async getVehicles(): Promise<Vehicle[]> {
    await delay(300);
    return mockData.vehicles;
  },

  async getVehicle(id: string): Promise<Vehicle | null> {
    await delay(200);
    return mockData.vehicles.find(vehicle => vehicle.id === id) || null;
  },

  async createVehicle(vehicle: Omit<Vehicle, 'id'>): Promise<Vehicle> {
    await delay(400);
    const newVehicle: Vehicle = {
      ...vehicle,
      id: `VEH-${String(mockData.vehicles.length + 1).padStart(4, '0')}`,
    };
    mockData.vehicles.unshift(newVehicle);
    return newVehicle;
  },

  async updateVehicle(id: string, updates: Partial<Vehicle>): Promise<Vehicle | null> {
    await delay(300);
    const index = mockData.vehicles.findIndex(vehicle => vehicle.id === id);
    if (index === -1) return null;
    
    mockData.vehicles[index] = {
      ...mockData.vehicles[index],
      ...updates,
    };
    return mockData.vehicles[index];
  },

  async deleteVehicle(id: string): Promise<boolean> {
    await delay(200);
    const index = mockData.vehicles.findIndex(vehicle => vehicle.id === id);
    if (index === -1) return false;
    
    mockData.vehicles.splice(index, 1);
    return true;
  },

  // 路线管理
  async getRoutes(): Promise<Route[]> {
    await delay(300);
    return mockData.routes;
  },

  async getRoute(id: string): Promise<Route | null> {
    await delay(200);
    return mockData.routes.find(route => route.id === id) || null;
  },

  async createRoute(route: Omit<Route, 'id'>): Promise<Route> {
    await delay(400);
    const newRoute: Route = {
      ...route,
      id: `ROUTE-${String(mockData.routes.length + 1).padStart(3, '0')}`,
    };
    mockData.routes.unshift(newRoute);
    return newRoute;
  },

  async updateRoute(id: string, updates: Partial<Route>): Promise<Route | null> {
    await delay(300);
    const index = mockData.routes.findIndex(route => route.id === id);
    if (index === -1) return null;
    
    mockData.routes[index] = {
      ...mockData.routes[index],
      ...updates,
    };
    return mockData.routes[index];
  },

  async deleteRoute(id: string): Promise<boolean> {
    await delay(200);
    const index = mockData.routes.findIndex(route => route.id === id);
    if (index === -1) return false;
    
    mockData.routes.splice(index, 1);
    return true;
  },

  // 财务管理
  async getFinancials(params?: { type?: string; page?: number; limit?: number }): Promise<{ data: Financial[]; total: number }> {
    await delay(300);
    let filteredFinancials = mockData.financials;
    
    if (params?.type) {
      filteredFinancials = filteredFinancials.filter(f => f.type === params.type);
    }
    
    const page = params?.page || 1;
    const limit = params?.limit || 10;
    const start = (page - 1) * limit;
    const end = start + limit;
    
    return {
      data: filteredFinancials.slice(start, end),
      total: filteredFinancials.length,
    };
  },

  async createFinancial(financial: Omit<Financial, 'id'>): Promise<Financial> {
    await delay(400);
    const newFinancial: Financial = {
      ...financial,
      id: `FIN-${String(mockData.financials.length + 1).padStart(6, '0')}`,
    };
    mockData.financials.unshift(newFinancial);
    return newFinancial;
  },

  async updateFinancial(id: string, updates: Partial<Financial>): Promise<Financial | null> {
    await delay(300);
    const index = mockData.financials.findIndex(financial => financial.id === id);
    if (index === -1) return null;
    
    mockData.financials[index] = {
      ...mockData.financials[index],
      ...updates,
    };
    return mockData.financials[index];
  },

  async deleteFinancial(id: string): Promise<boolean> {
    await delay(200);
    const index = mockData.financials.findIndex(financial => financial.id === id);
    if (index === -1) return false;
    
    mockData.financials.splice(index, 1);
    return true;
  },

  // 货物管理
  async getCargos(params?: { page?: number; limit?: number }): Promise<{ data: Cargo[]; total: number }> {
    await delay(300);
    const page = params?.page || 1;
    const limit = params?.limit || 10;
    const start = (page - 1) * limit;
    const end = start + limit;
    
    return {
      data: mockData.cargos.slice(start, end),
      total: mockData.cargos.length,
    };
  },

  async getCargo(id: string): Promise<Cargo | null> {
    await delay(200);
    return mockData.cargos.find(cargo => cargo.id === id) || null;
  },

  async createCargo(cargo: Omit<Cargo, 'id'>): Promise<Cargo> {
    await delay(400);
    const newCargo: Cargo = {
      ...cargo,
      id: `CARGO-${String(mockData.cargos.length + 1).padStart(4, '0')}`,
    };
    mockData.cargos.unshift(newCargo);
    return newCargo;
  },

  async updateCargo(id: string, updates: Partial<Cargo>): Promise<Cargo | null> {
    await delay(300);
    const index = mockData.cargos.findIndex(cargo => cargo.id === id);
    if (index === -1) return null;
    
    mockData.cargos[index] = {
      ...mockData.cargos[index],
      ...updates,
    };
    return mockData.cargos[index];
  },

  async deleteCargo(id: string): Promise<boolean> {
    await delay(200);
    const index = mockData.cargos.findIndex(cargo => cargo.id === id);
    if (index === -1) return false;
    
    mockData.cargos.splice(index, 1);
    return true;
  },
};